import ajax from './request'
import classData from '../json/class.json'
import studentData from '../json/student.json'

function getClassesFromRap2() {
    return ajax({
        url: '/api/v1/classes',
        method: 'GET'
    })
}

function getStudentsFromRap2() {
    return ajax({
        url: '/api/v1/students',
        method: 'GET'
    })
}

function getExamsFromRap2() {
    return ajax({
        url: '/api/v1/exams',
        method: 'GET'
    })
}

function getScoresFromRap2() {
    return ajax({
        url: '/api/v1/score',
        method: 'GET'
    })
}

// 引入随机数据，从rap2引入
export const setDataFromRap2 = async () => {
    const classesData = await getClassesFromRap2()
    if (classesData.code === 0) {
        localStorage.setItem('classData', JSON.stringify(classesData.data))
    }
    const studentsData = await getStudentsFromRap2()
    if (studentsData.code === 0) {
        localStorage.setItem('studentData', JSON.stringify(studentsData.data))
    }
    const examsData = await getExamsFromRap2()
    if (examsData.code === 0) {
        localStorage.setItem('examData', JSON.stringify(examsData.data))
    }
    const scoreData = await getScoresFromRap2()
    if (scoreData.code === 0) {
        localStorage.setItem('scoreData', JSON.stringify(scoreData.data))
    }
    return Promise.resolve({ code: 0 })
}

// 清空数据
export const initData = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            localStorage.removeItem('classData')
            localStorage.removeItem('studentData')
            localStorage.removeItem('examData')
            localStorage.removeItem('scoreData')
            resolve({ code: 0 })
        }, 500)
    })
}

// 引入真实数据，从本地json文件引入
export const setDataFromJSON = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            localStorage.setItem('classData', JSON.stringify(classData.data))
            localStorage.setItem(
                'studentData',
                JSON.stringify(studentData.data)
            )
            resolve({ code: 0 })
        }, 500)
    })
}
